// 取消令牌
class CancelToken {
  bool _isCancelled = false;

  void cancel() {
    _isCancelled = true;
  }

  bool get isCancelled => _isCancelled;
}

// 重试管理器
class FutureManager {
  // 私有静态实例
  static final FutureManager _instance = FutureManager._internal();

  // 静态 getter
  static FutureManager get instance => _instance;

  // 私有构造函数
  FutureManager._internal();

  /// 轮询任务
  /// [task] 要执行的异步任务
  /// [milliseconds] 每次重试的间隔时间（毫秒）
  /// [maxAttempts] 最大重试次数
  /// [cancelToken] 可选的取消令牌
  /// [continueOnError] 无论结果成功与否都继续重试
  Future<T?> pollingTask<T>(
    Future<T> Function() task, {
    required int milliseconds,
    required int maxAttempts,
    CancelToken? cancelToken,
    // 无论结果成功与否都继续重试
    bool continueOnError = false,
  }) {
    int attempt = 0;
    T? lastResult;

    Future<T?> executeTask() async {
      if (cancelToken?.isCancelled == true) {
        return lastResult;
      }
      try {
        final result = await task();
        lastResult = result;
        attempt++;
        if (attempt >= maxAttempts) {
          return result;
        }
        if (continueOnError) {
          await Future.delayed(Duration(milliseconds: milliseconds));
          return executeTask();
        } else {
          return result;
        }
      } catch (e) {
        attempt++;
        if (attempt >= maxAttempts) {
          rethrow;
        }
        await Future.delayed(Duration(milliseconds: milliseconds));
        return executeTask();
      }
    }

    return executeTask();
  }
}
